﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Sdk;

namespace BulkDelete
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            txtOrganizationName.Text = Properties.BUSettings.Default.Organization;
            txtUser.Text = Properties.BUSettings.Default.Username;
            txtPassword.Text = Properties.BUSettings.Default.Password;

            updateConnectionString();
        }

        private void txtEntityNames_TextChanged(object sender, TextChangedEventArgs e)
        {
            lblEntityCount.Content = txtEntityNames.LineCount;
        }

        private void txtUser_TextChanged(object sender, TextChangedEventArgs e)
        {
            updateConnectionString();
        }

        private void txtPassword_TextChanged(object sender, TextChangedEventArgs e)
        {
            updateConnectionString();
        }
     

        private void txtOrganization_TextChanged(object sender, TextChangedEventArgs e)
        {
            updateConnectionString();
        }

        private void updateConnectionString()
        { 
            txtConnectionString.Text = String.Format(Properties.BUSettings.Default.CSTemplate, txtOrganizationName.Text, txtUser.Text, txtPassword.Text);
        }

        private void btnResetConfiguration_Click(object sender, RoutedEventArgs e)
        {
            txtOrganizationName.Text = Properties.BUSettings.Default.Organization;
            txtUser.Text = Properties.BUSettings.Default.Username;
            txtPassword.Text = Properties.BUSettings.Default.Password;

            updateConnectionString();
        }

        private void btnSaveConfiguration_Click(object sender, RoutedEventArgs e)
        {
           Properties.BUSettings.Default.Organization = txtOrganizationName.Text;
           Properties.BUSettings.Default.Username = txtUser.Text;
           Properties.BUSettings.Default.Password = txtPassword.Text;
           Properties.BUSettings.Default.Save();
        }

        private void btnClearConfiguration_Click(object sender, RoutedEventArgs e)
        {
            txtOrganizationName.Text = txtUser.Text = txtPassword.Text = "";

            updateConnectionString();
        }

        private void btnRun_Click(object sender, RoutedEventArgs e)
        {
            txtlog.Text = "";

            List <string> entities = getEntityNames();

            logAcion("Entities Identified: " + entities.Count);

            int successDeletes = 0;
            int successDeletedRecords = 0;

            for (int i = 0; i < entities.Count; i++)
            {
                string entityName = entities[i];
                logAcion("Processing ("+(i+1)+"/" + entities.Count + "): " + entityName);

               int sucessdeletedRecordsLocal = deleteEntityRecordsFromCRM(entityName);

                if (sucessdeletedRecordsLocal > 0)
                {
                    ++successDeletes;
                    successDeletedRecords += sucessdeletedRecordsLocal;
                }
            }

            logAcion("---> Bulk Delete Completed. Sucessfully deleted " + successDeletes + " entities. And a Total of "+ successDeletedRecords + " records");
        }

        private int deleteEntityRecordsFromCRM(string entityName)
        {
            CrmConnection crmConnection = CrmConnection.Parse(txtConnectionString.Text);
            Microsoft.Xrm.Client.CrmOrganizationServiceContext crmContext = new CrmOrganizationServiceContext(crmConnection);

            Microsoft.Xrm.Sdk.Query.QueryExpression query = new Microsoft.Xrm.Sdk.Query.QueryExpression();
            query.EntityName = entityName;
            int successDeletes = 0;

            try
            {
                EntityCollection entityRecords = crmContext.RetrieveMultiple(query);
                int count = entityRecords.Entities.Count;

                logAcion("-- " + entityRecords.Entities.Count.ToString() + " records to process.");

                for (int i = 0; i < entityRecords.Entities.Count; i++)
                {
                    try
                    {
                        Entity et = entityRecords.Entities[i];
                        crmContext.Delete(et.LogicalName, et.Id);
                        logAcion("-- Record " + (i + 1) + " of " + entityRecords.Entities.Count.ToString() + " " + et.LogicalName + " " + et.Id.ToString());
                        ++successDeletes;
                    }
                    catch (Exception ex)
                    {
                        logAcion("-- Failed. Details: " + ex.Message);
                        continue;
                    }
                }
            }
            catch (Exception ex)
            {
                logAcion("-- Failed to get records of " + entityName + " . Details: " + ex.Message);
            }

            return successDeletes;
        }
     
        private void logAcion(string message)
        {
            DateTime d = DateTime.Now;
            txtlog.Text +=  d.ToLocalTime() +  " | " + message + Environment.NewLine;
            txtlog.Refresh();
        }

        private List<string> getEntityNames()
        {
            List<string> entities = new List<string>();

            for (int i = 0; i < txtEntityNames.LineCount; i++)
            {
                string entityName = txtEntityNames.GetLineText(i);

                if (!string.IsNullOrEmpty(entityName))
                {
                    entityName = entityName.Replace("\r\n", "");
                    if (!string.IsNullOrEmpty(entityName)) entities.Add(entityName);
                }
            }

            return entities;
        }

    }
}
